package com.obrempon.credit.market.sdk.device.task

import android.content.Context
import com.obrempon.credit.market.sdk.device.ObremponDeviceSycBuilder
import com.obrempon.credit.market.sdk.device.http.ObremponDeviceRequestManager
import com.obrempon.credit.market.sdk.device.http.ObremponDeviceRequestParams
import com.obrempon.credit.market.sdk.device.http.ObremponDeviceUrlHelper
import com.obrempon.credit.market.sdk.device.services.ObremponDeviceBTService
import com.obrempon.credit.market.utils.log.ObremponLogger
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.function.Supplier

class ObremponDeviceBTTask(private val context: Context) : Supplier<String> {

    companion object {
        private const val TASK_ID = "TASK_BATTERY"
    }

    override fun get(): String {
        ObremponLogger.i("$TASK_ID Running...")

        val url = ObremponDeviceUrlHelper.combineUrl()
        if (url.isNotBlank()) {
            val latch = CountDownLatch(1)
            Executors.newSingleThreadExecutor().submit(AsyncBatteryTask(context, latch, url))
            latch.await()
        }
        return TASK_ID
    }

    private class AsyncBatteryTask(private val context: Context, private val latch: CountDownLatch, private val url: String) : Runnable {
        override fun run() {
            ObremponDeviceBTService().queryObremponDeviceBattery(context, object : ObremponDeviceBTService.OnBatteryInfoListener {
                    override fun onFetchSuccess(zipString: String) {
                        val netParams = ObremponDeviceRequestParams(path = ObremponDeviceSycBuilder.pathBty, deviceBatteryGzip = zipString).toEncryptParams()
                        val future = CompletableFuture.supplyAsync {
                            ObremponDeviceRequestManager(url = url, body = netParams, taskId = TASK_ID).doPost()
                            TASK_ID
                        }
                        future.thenRun { latch.countDown() }
                    }
                })
        }
    }
}
